package com.turevskiy.android.tictactoe;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;

public class SingleCellView extends View {
	Paint paint = new Paint();
	public int stateIndex;
	public MainActivity host;

	float x1;
	float x2;
	float y1;
	float y2;
	RectF rect;

	public SingleCellView(Context context, AttributeSet attrs) throws Exception {
		super(context, attrs);

		host = (MainActivity) getContext();

		host.cellViews.add(this);

		if (this.getId() == R.id.simpledraw1)
			stateIndex = 0;
		else if (this.getId() == R.id.simpledraw2)
			stateIndex = 1;
		else if (this.getId() == R.id.simpledraw3)
			stateIndex = 2;
		else if (this.getId() == R.id.simpledraw4)
			stateIndex = 3;
		else if (this.getId() == R.id.simpledraw5)
			stateIndex = 4;
		else if (this.getId() == R.id.simpledraw6)
			stateIndex = 5;
		else if (this.getId() == R.id.simpledraw7)
			stateIndex = 6;
		else if (this.getId() == R.id.simpledraw8)
			stateIndex = 7;
		else if (this.getId() == R.id.simpledraw9)
			stateIndex = 8;
		else
			throw new Exception("Unknown cell found: " + this.getId());

		if (host.getCell(stateIndex) != 1 && host.getCell(stateIndex) != 2) {
			host.setCell(stateIndex, 0);
		}

		paint.setColor(Color.BLACK);
		paint.setStyle(Paint.Style.STROKE);

		this.setClickable(true);
		this.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				SingleCellView scv = (SingleCellView) v;
				scv.processViewClick();
			}
		});
	}

	protected void processViewClick() {
		if (host.getCell(stateIndex) == 0) {
			host.setCell(stateIndex, host.getNextTurn());
			invalidate();
			host.checkWinner();
		}
	}

	@Override 
    protected void onSizeChanged(int w, int h, int oldw, int oldh) 
    {
    	x1 = (float)(w * 0.1); 
    	y1 = (float)(h * 0.1); 
    	x2 = (float)(w * 0.9);
    	y2 = (float)(h * 0.9);
    	rect = new RectF(x1,y1,x2,y2);
    }

	@Override
	public void onDraw(Canvas canvas) {

		if (host.getCell(stateIndex) == 1) {
			canvas.drawLine(x1, y1, x2, y2, paint);
			canvas.drawLine(x1, y2, x2, y1, paint);
		} else if (host.getCell(stateIndex) == 2) {
			canvas.drawOval(rect, paint);
		}
	}
}